package com.java1412.controller.api;

import com.java1412.entity.User;
import com.java1412.service.UserService;
import com.java1412.utils.ConstantUtil;
import com.java1412.utils.ResponseUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author java1412
 * @since 2023-06-20 16:46:44
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/{id}")
    public Object findById(@PathVariable("id") Integer id) {
        return userService.findById(id);
    }

    @PostMapping("/login")
    public Object login(User user, HttpSession session) {
        ResponseUtil r = userService.findByUsername(user);
        if (r.getCode().intValue() == 200) {
            // 登录成功才需要放session
            session.setAttribute(ConstantUtil.LOGIN_USER_KEY, r.getData());
        }
        return r;
    }

    // 获取登录的用户信息
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(HttpSession session) {
        // 获取当前登录的用户对象
        Object loginUser = session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        return ResponseUtil.ok("登录的用户信息", loginUser);
    }

    // 定义注销接口
    @GetMapping("/logout")
    public Object logout(HttpSession session) {
        session.invalidate(); // 使当前session失效
        return ResponseUtil.ok("注销成功");
    }

    /**
     * 注册功能
     *
     * @param user 用户数据
     * @param uuid 根据该uuid去redis找验证码和手机号
     * @param code 验证码
     * @return
     */
    @PostMapping("/register")
    public Object register(User user, String uuid, String code) {
        ResponseUtil r = userService.register(user, uuid, code);
        return r;
    }
}
